<?php
use Base\AdminController;
use JetBrains\PhpStorm\NoReturn;
use Traits\DataTree;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;
use WeChat\Menu;
use Yaf\Dispatcher;

/**
 * 菜单管理
 */
class WechatMenuController extends AdminController
{
    use DataTree;

	protected string $table = 'wechat_menus';

    protected string $model = "WechatMenu";

    /**
     * 获取所有父级数据ID
     * @需求：通过ID获取所有父级数据
     * @param  array $data 数据
     * @param  int $id 节点ID
     * @return array  $result 结果数组
     */
    protected function getAllParentIds(array $data, int $id): array
    {
        $result = array();
        if (isset($data[$id]['parent_id'])) {
            while (@$data[$id]['parent_id']) {
                $result[] = $data[$id]['parent_id'];
                $id = $data[$id]['parent_id'];
            }
        }
        return $result;
    }

    /**
     * 获取所有数据
     * @return void
     */
    #[NoReturn] public function getDataAction(): void
    {
        try {
            $data = WechatMenuModel::query()
			->when(Request::input("title"), function ($query,$value){
                $query->where("title",'like', '%'.$value.'%');
            })
			->get()
			->toArray();
            $data = $this->getTree($data, 'parent_id');
            $this->apiSuccess($data,'获取成功',20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

    /**
     * 获取所有1、2级菜单数据
     * @return void
     */
    #[NoReturn]  public function getSelectDataAction(): void
    {
        $data = WechatMenuModel::query()->selectRaw("id as value,title as label")
            ->where("parent_id", 0)->get()->toArray();
        $this->apiSuccess($data,'获取成功',20000);
    }

    /**
     * 添加菜单
     * @return void
     */
	#[NoReturn]  public function addAction(): void
    {
		if (Request::input("parent_id")==0) {
			$num = WechatMenuModel::query()->where("parent_id", 0)->count();
			if($num>=3) $this->apiError("一级菜单个数应为1~3个");
		}else {
			$num = WechatMenuModel::query()->where("parent_id", Request::input("parent_id"))->count();
			if($num>=5) $this->apiError("二级菜单个数应为1~5个");
		}
        parent::addAction();
    }

    /** 同步菜单
     * @return void
     */
	#[NoReturn]  public function syncDataAction(): void
    {
		try {
            $config = Config::get("wechat");
            $menu = new Menu([
                'appid' => $config['AppId'],
                'appsecret' => $config['AppSecret']
            ]);
			$res = $menu->delete();
			if ($res['errcode']!=0)  $this->apiError($res['errcode']."-".$res['errmsg']);
			$data = WechatMenuModel::query()->selectRaw("id,parent_id,title as name,type,appid,url,pagepath,`key`")->get()->toArray();
			$keyType = [
				"rselfmenu_0_0"=>"scancode_waitmsg",
				"rselfmenu_0_1"=>"scancode_push",
				"rselfmenu_1_0"=>"pic_sysphoto",
				"rselfmenu_1_1"=>"pic_photo_or_album",
				"rselfmenu_1_2"=>"pic_weixin",
				"rselfmenu_2_0"=>"location_select",
			];
			foreach($data as $key=>$vo){
				if($vo['type']=='click') {
					$data[$key]['type'] = $keyType[$vo['key']];
					$data[$key]['url'] = "";
				}
			}
            $data = $this->getWechatTree($data, 'parent_id');
            $data = $menu->create($data);
            if ($data['errcode']==0) {
                $this->apiSuccess([],'同步成功',20000);
            }else {
                $this->apiError($data['errcode']."-".$data['errmsg']);
            }
        } catch (InvalidResponseException|LocalCacheException $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }
}
